import 'dart:developer';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/service/match_service.dart';
import 'package:sports_new/entity/ai/ai_combo_entity.dart';
import 'package:sports_new/entity/ai/ai_item_entity.dart';
import 'package:sports_new/entity/ai/ai_date_entity.dart';
import 'package:sports_new/entity/pay/usable_coupon.dart';
import 'package:sports_new/server/api/ai_api.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/pick/ai/ai_type.dart';
import '../../entity/ai/ai_info_entity.dart';
import '../../entity/ai/ai_pay_entity.dart';
import '../../entity/ai/ai_rate_entity.dart';
import '../../entity/pay/recharge_entity.dart';
import '../../server/api/coupon_api.dart';
import '../../server/api/pay_api.dart';
import '../../utils/toast_utils.dart';
import '../../widgets/bottom_picker_widget.dart';
import '../../widgets/pay_bottom_sheet.dart';

class AiModelLogic extends GetxController with GetTickerProviderStateMixin {
  final AiType? type = Get.arguments is AiType
      ? Get.arguments
      : AiType.getTypeByRoute(Get.currentRoute);
  int? roomId = Get.parameters['roomId'].toInt();
  AiDateEntity? data;
  AiComboEntity? combo;
  List<AiInfoEntity>? aiInfo;
  List<AiRateEntity>? aiInfoRate;
  List<DateTime> dayList = [];
  List<int> showAllHit = [];
  int _tabIndex = 0;
  int _needReGet = 22;
  RightCheck? check;
  String? price;
  String? realPrice;
  List<int> oneLevelId = Get.find<MatchService>().zqOneLevelId;
  EasyRefreshController refreshController =
      EasyRefreshController(controlFinishLoad: true);
  late List<String> text = List.generate(7, (index) => "");
  List<String> _filterCount = List.generate(7, (index) => "");
  late List<List<AiItemEntity>> matchList = List.generate(7, (index) => []);
  late List<List<AiItemEntity>> notHitList = List.generate(7, (index) => []);
  List<List<DetailItems>> comboList = List.generate(7, (index) => []);
  List<int> loadIndex = List.generate(4, (index) => 1);
  late List<bool> isLoading = List.generate(7, (index) => true);
  late TabController tabController;
  final List<List<String>> _filter = List.generate(7, (index) => ["全部比赛"]);
  final List<int> _filterIndex = List.generate(7, (index) => 0);
  final GlobalKey infoKey = GlobalKey();
  double _infoHeight = 0;

  int get tabIndex => _tabIndex;
  int get needReGet => _needReGet;
  List<DetailItems> get comboFilterList => comboList[tabIndex].where((e) {
        switch (filter) {
          default:
            return true;
        }
      }).toList();
  List<AiItemEntity> get matchFilterList => matchList[tabIndex].where((e) {
        switch (filter) {
          default:
            return true;
        }
      }).toList();
  List<AiItemEntity> get notHitFilterList => notHitList[tabIndex].where((e) {
        switch (filter) {
          default:
            return true;
        }
      }).toList();
  int get filterIndex => _filterIndex[tabIndex];
  String get filter => _filter[tabIndex][filterIndex];
  double get infoHeight => _infoHeight;
  String? get logo => type == AiType.combo ? combo?.logo : data?.logo;
  String? get name => type == AiType.combo ? combo?.name : data?.name;
  String? get info => type == AiType.combo ? combo?.info : data?.info;
  String get filterCount => _filterCount[tabIndex];

  set filterCount(String value) {
    _filterCount[tabIndex] = value;
    update();
  }

  set infoHeight(double value) {
    _infoHeight = value;
    update();
  }

  set needReGet(int value) {
    _needReGet = value;
    update();
  }

  set tabIndex(int value) {
    _tabIndex = value;
    update();
  }

  @override
  void onReady() async {
    await getCheck();
    switch (type) {
      case AiType.combo:
        await getCombo();
        getHeight();
        break;
      default:
        await getData();
        getHeight();
    }
    tabController.addListener(() {
      if (tabIndex != tabController.index) {
        tabIndex = tabController.index;
        if (type == AiType.combo
            ? comboList[tabController.index].isEmpty
            : matchList[tabController.index].isEmpty) {
          switch (type) {
            case AiType.combo:
              getCombo(index: tabController.index);
              break;
            default:
              getData(index: tabController.index);
          }
          needReGet = needReGet + tabController.index;
        }
      }
      refreshController.resetFooter();
    });
    super.onReady();
  }

  void getHeight() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final TextPainter textPainter = TextPainter(
          text: TextSpan(
              text: data?.info ?? "",
              style: const TextStyle(fontSize: 12, color: Colors.white)),
          textDirection: TextDirection.ltr)
        ..layout(minWidth: 0, maxWidth: Get.width - 40);
      if (dayList.hasValue) {
        infoHeight = 130 +
            textPainter.size.height +
            10 +
            (aiInfo?.length ?? 0) * 21 +
            (aiInfo?.length != 0 ? 20 : 0);
        log("标签高度------${(aiInfo?.length ?? 0) * 21 + (aiInfo?.length != 0 ? 20 : 0)}");
      }
    });
  }

  Future getData({int? index}) async {
    var entity = await AiApi.getAi(
        index == null ? "" : dayList[index].formatedString('yyyy-MM-dd'),
        type?.tag ?? "");
    if (index == null) {
      data = entity;
      dayList
          .addAll(data?.dayList?.map((e) => DateTime.parse(e.day ?? "")) ?? []);
      tabIndex = dayList.indexWhere((e) => e.day == DateTime.now().day);
      for (var i = 0; i < (data?.dayList?.length ?? 0); i++) {
        if (data?.dayList?[i].allHit == true) showAllHit.add(i);
        if (data?.dayList?[i].selected == true) tabIndex = i;
      }
      matchList[tabIndex] = data?.matchList ?? [];
      notHitList[tabIndex] = data?.notHitList ?? [];
      text[tabIndex] = data?.leftText ?? "";
      tabController = TabController(
          length: dayList.length, vsync: this, initialIndex: tabIndex);
      isLoading[tabIndex] = false;
    } else {
      data?.matchList = entity?.matchList;
      data?.notHitList = entity?.notHitList;
      data?.dayList = entity?.dayList;
      data?.leftText = entity?.leftText;
      matchList[index] = data?.matchList ?? [];
      notHitList[index] = data?.notHitList ?? [];
      text[index] = data?.leftText ?? "";
      isLoading[index] = false;
    }
    int jcNo = matchList[tabIndex]
        .where((element) => element.jcMatchNo.hasValue == true)
        .length;
    int sfcNo = matchList[tabIndex]
        .where((element) => element.sfcMatchNo.hasValue == true)
        .length;
    int dcNo = matchList[tabIndex]
        .where((element) => element.dcMatchNo.hasValue == true)
        .length;
    _filter[tabIndex] = ["全部比赛"];
    if (matchList[tabIndex]
        .any((element) => oneLevelId.contains(element.leagueId))) {
      _filter[tabIndex].add("一级");
    }
    if (jcNo != 0) {
      _filter[tabIndex].add("竞足");
    }
    if (dcNo != 0) {
      _filter[tabIndex].add("单场");
    }
    if (sfcNo != 0) {
      _filter[tabIndex].add("十四场");
    }
    log(_filter[tabIndex].toString());
    filterCount =
        "今日共有${matchFilterList.length + (type == AiType.lm ? notHitFilterList.length : 0)}场比赛";
    update();
  }

  Future getCombo({int? index}) async {
    var entity = await AiApi.getCombo(
        index == null ? "" : dayList[index].formatedString('yyyy-MM-dd'),
        type?.tag ?? "");
    if (index == null) {
      combo = entity;
      dayList.addAll(
          combo?.dayList?.map((e) => DateTime.parse(e.day ?? "")) ?? []);
      tabIndex = dayList.indexWhere((e) => e.day == DateTime.now().day);
      for (var i = 0; i < (combo?.dayList?.length ?? 0); i++) {
        if (combo?.dayList?[i].allHit == true) showAllHit.add(i);
        if (combo?.dayList?[i].selected == true) tabIndex = i;
      }
      comboList[tabIndex] = combo?.comboList ?? [];
      text[tabIndex] = combo?.leftText ?? "";
      tabController = TabController(
          length: dayList.length, vsync: this, initialIndex: tabIndex);
      isLoading[tabIndex] = false;
    } else {
      combo?.comboList = entity?.comboList;
      data?.dayList = entity?.dayList;
      data?.leftText = entity?.leftText;
      comboList[index] = combo?.comboList ?? [];
      text[index] = combo?.leftText ?? "";
      isLoading[index] = false;
    }
    int jcNo = comboList[tabIndex]
        .where((element) =>
            element.items?.any((e) => e.jcMatchNo.hasValue == true) ?? false)
        .length;
    int sfcNo = comboList[tabIndex]
        .where((element) =>
            element.items?.any((e) => e.sfcMatchNo.hasValue == true) ?? false)
        .length;
    int dcNo = comboList[tabIndex]
        .where((element) =>
            element.items?.any((e) => e.dcMatchNo.hasValue == true) ?? false)
        .length;
    if (comboList[tabIndex].any((element) =>
        element.items?.any((e) => oneLevelId.contains(e.leagueId)) ?? false)) {
      _filter[tabIndex].add("一级");
    }
    if (jcNo != 0 && jcNo != comboList[tabIndex].length) {
      _filter[tabIndex].add("竞足");
    }
    if (dcNo != 0 && dcNo != comboList[tabIndex].length) {
      _filter[tabIndex].add("单场");
    }
    if (sfcNo != 0 && sfcNo != comboList[tabIndex].length) {
      _filter[tabIndex].add("十四场");
    }
    filterCount =
        "今日${type == AiType.lm ? "命中" : "共有"}${comboFilterList.length}场比赛";
    update();
  }

  Future getCheck() async {
    check = await AiApi.getCheck(type?.id ?? 0);
    aiInfo = await AiApi.getAiInfo(type?.id ?? 0);
    aiInfoRate = await AiApi.getAiRate(type?.id ?? 0);
    List<AiPrice>? aiPrice = (await PayApi.getAiPay(type?.id ?? 0,
            roomId: Get.parameters["roomId"].toInt()))
        .price;
    if (aiPrice?.length != 0) {
      double p = aiPrice?.first.price?.split("球币").join().toDouble() ?? 0;
      var coupons = User.isLogin
          ? await CouponApi.use1Coupons(gold: p, scene: PayScene.ai)
          : [];
      double coupon =
          coupons?.filterOrNull((item) => item.autoSelect == 1)?.first.gold ??
              0;
      realPrice = (p - coupon).toStringAsFixed(2);
      price = p.toStringAsFixed(2);
    }
    update();
  }

  Future getRefresh() async {
    getCheck();
    for (var i = tabIndex; i < dayList.length; i++) {
      switch (type) {
        case AiType.combo:
          getCombo(index: i);
          break;
        default:
          getData(index: i);
      }
    }
  }

  Future showDatePicker() async {
    _filterIndex[tabIndex] = await Get.bottomSheet(BottomPickerWidget(
      _filter[tabIndex],
      title: '选择比赛类型',
      initialIndex: _filterIndex[tabIndex],
    ));
    filterCount =
        "今日${type == AiType.lm ? "命中" : "共有"}${type == AiType.combo ? comboFilterList.length : matchFilterList.length}场比赛";
    update();
  }

  String ticketName(AiItemEntity item) {
    String name = '';
    if (filter == "竞足") {
      name = item.jcMatchNo ?? '';
    } else if (filter == "单场") {
      name = item.dcMatchNo ?? '';
    } else if (filter == "十四场") {
      name = item.sfcMatchNo ?? '';
    } else {
      name = ((item.jcMatchNo ?? item.dcMatchNo) ?? item.sfcMatchNo) ?? '';
    }
    return name;
  }

  Future toPay(AiPrice price) async {
    var x = double.parse(price.price!.split(RegExp(r"[\u4e00-\u9fa5]")).join());
    double money = x;
    final coupons = await CouponApi.use1Coupons(
        gold: money, scene: PayScene.aiSingle, otherId: '');
    final PayResult? result = await Get.bottomSheet(
        isScrollControlled: true,
        PayBottomSheet(
            payInfo: PayInfo(
                price: money.toString(),
                payScene: PayScene.aiSingle,
                buyId: "${price.id}-${price.aiId}",
                coupons: coupons)));
    if (result != null && result.toPay == PayStatus.goldPay) {
      var s = await PayApi.aiOrder(
        price.id,
        aiId: price.aiId,
        couponGold: result.coupon?.gold,
        couponId: result.coupon?.id,
      );
      if (s == true) {
        Utils.onEvent('pay_done');
        getRefresh();
      } else {
        Utils.onEvent('aixq_zfyd_qxzf');
      }
    } else if (result?.toPay == PayStatus.directPay) {
      Utils.onEvent('aixq_zfyd_qrzf');
      getRefresh();
    } else {
      Utils.onEvent('aixq_zfyd_qxzf');
      ToastUtils.show("购买失败");
    }
    User.fetchUserInfo(fetchFocus: false);
  }
}
